//
//  WNLoginManager.m
//  Whatnet_iOS
//
//  Created by 北辰 on 2019/4/19.
//  Copyright © 2019 什么网络. All rights reserved.
//

#import "WNLoginManager.h"
#import "WANavigationController.h"

#define WNUserInfoPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"WNUserInfo.coding"]

@interface WNLoginManager ()

@property(nonatomic, assign) BOOL loginVCIsVisible;
@property(nonatomic, assign) NSInteger is_failLogin ; //登录失败次数

@end

@implementation WNLoginManager 

+ (instancetype)manager{
    static WNLoginManager * loginManager = nil;
    static dispatch_once_t downloadToken;
    dispatch_once(&downloadToken, ^{
        loginManager = [[WNLoginManager alloc] init];
        if ([[NSFileManager defaultManager] fileExistsAtPath:WNUserInfoPath]) {
            @try {
                NSData *codingData = [[NSData alloc] initWithContentsOfFile:WNUserInfoPath];
                NSKeyedUnarchiver *unachiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:codingData];
                loginManager.userInfo = [unachiver decodeObjectForKey:@"WNUserInfo"];
                [unachiver finishDecoding];
                
            } @catch (NSException *exception) {
                NSLog(@"WNUserInfo 出错%@",exception);
                loginManager.userInfo = [WNUserInfo new];
            } @finally {
                
            }
        } else {
            loginManager.userInfo = [WNUserInfo new];
        }
    });
    return loginManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)setUserIDAndToken:(NSDictionary *)dict{
    [self.userInfo setDataWithDict:dict];
    [self saveUserInfo];
}

/**
 是否在线
 */
- (BOOL)isloginOnline{
    if (self.userInfo.userid > 0 && self.userInfo.password.length > 0) {
        return YES;
    }
    return NO;
}

/**
 是否完成了认证
 */
- (BOOL)isAuthentication{
    //下面四个都填了才算认证
    if (self.userInfo.name > 0 && self.userInfo.cardid.length > 0 && self.userInfo.bankname.length > 0 && self.userInfo.cardnum.length > 0) {
        return YES;
    }
    return NO;
}

/**
 是否可发布任务
 */
- (BOOL)canPublish{
    return self.userInfo.viplevel.integerValue >= 0;
}

/**
 退出登录
 */
- (void)loginOut{
    _userInfo = [WNUserInfo new];
    //可能
    [self clearUserInfo];
    [self loginOutIM];
}

/**
 用户未定位
 
 @return 返回YES表示未定位
 */
- (BOOL)noLocation{
    return YES;
}

/**
 是否已经实名认证
 */
- (BOOL)isIdentityAuthentication;{
    return YES;
}

/**
 更新实名认证
 
 @param tag 是否成功
 */
- (void)updateIdentityAuthentication:(BOOL)tag{
//    self.userInfo.authStatus = tag;
    [self saveUserInfo];
}

/**
 存储模型
 */
- (BOOL)saveUserInfo{
    NSMutableData *mutableData = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutableData];
    [archiver encodeObject:self.userInfo forKey:@"WNUserInfo"];
    [archiver finishEncoding];
    if(![mutableData writeToFile:WNUserInfoPath atomically:YES]) {
        NSLog(@"写入WNUserInfoPath的归档文件失败");
        return NO;
    }
    return YES;
}

/**
 清楚用户信息
 */
- (BOOL)clearUserInfo{
    self.userInfo = WNUserInfo.new;
    return [self saveUserInfo];
}

- (void)presentLoginView:(DismissBlcok)dismissBlock{
    if ([self loginVCIsVisible]) {
        return;
    }
    _loginVCIsVisible = YES;
    UIViewController*rootViewcontroller =[UIApplication sharedApplication].keyWindow.rootViewController;
    while (rootViewcontroller.presentedViewController) {
        rootViewcontroller = rootViewcontroller.presentedViewController;
    }
    WALoginController *loginVC = [WALoginController new];
    loginVC.dismissBlock = dismissBlock;
    @weakify(self)
    [loginVC setDismissBlock:^(BOOL loginSuccess) {
        @strongify(self)
        self->_loginVCIsVisible = NO;
        if (dismissBlock) {
            dismissBlock(loginSuccess);
        }
    }];
    WANavigationController *thirdNavigationController = [[WANavigationController alloc]
                                                   initWithRootViewController:loginVC];
    [thirdNavigationController setNavigationBarHidden:YES animated:NO];
    thirdNavigationController.modalPresentationStyle = UIModalPresentationFullScreen;
    [rootViewcontroller presentViewController:thirdNavigationController animated:YES completion:nil];
}

- (NSString *)getUDID{
    if ([[JIUUserDataManager readPassWord] isEqualToString:@""] || [[JIUUserDataManager readPassWord] isKindOfClass:NULL] || [JIUUserDataManager readPassWord] == nil) {
        NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [JIUUserDataManager savePassWord:uuid];
    }
    NSLog(@"唯一ID：%@",[JIUUserDataManager readPassWord]);
    return [JIUUserDataManager readPassWord];
}

/**
 //显示设置年龄和性别视图，用户信息必须完善
 */
- (void)showSetAgeAndGenderView{
}

/**
 登录IMxxx
 */
- (void)updateUserInfo:(DismissBlcok)dismissBlock{
    [WNBusinessRequest getUserInfoWithID:[@(self.userInfo.userid) stringValue] Succ:^(id  _Nonnull responseObject) {
           self.userInfo = [WNUserInfo yy_modelWithJSON:responseObject];
           [self saveUserInfo];
           [self deviceIsAuthentication];
        if (dismissBlock) {
            dismissBlock(nil);
        }
       } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
           
       }];
}

- (void)updateUserHeadImageAndUserInfo:(DismissBlcok)dismissBlock{
    [WNBusinessRequest getUserHeadImageSucc:^(id  _Nonnull responseObject) {
           self.userInfo = [WNUserInfo yy_modelWithJSON:responseObject];
           [self saveUserInfo];
           [self deviceIsAuthentication];
        if (dismissBlock) {
            dismissBlock(nil);
        }
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        
    }];
}

- (void)loginOutIM{
}

//登录页面是否已经显示
- (BOOL)loginVCIsVisible{
    return _loginVCIsVisible;
}

//z设备是否认证了
- (BOOL)deviceIsAuthentication{
    if (self.userInfo.appno.length > 0 && ![[self getUDID] isEqualToString:self.userInfo.appno]) {
        [WNTool show:@"您的账号已被冻结，有疑问请联系客服"];
        [self loginOut];
        [self presentLoginView:^(BOOL loginSuccess) {
            
        }];
        return NO;
    }
    return YES;
}

@end

@implementation NSObject (WNUser)
-(WNLoginManager *)loginManager{
    return [WNLoginManager manager];
}

- (NSInteger)userID_Int{
    return self.loginManager.userInfo.userid;
}

- (NSString *)userID_String{
    return [@(self.loginManager.userInfo.userid) stringValue];
}

+ (NSInteger)userID_Int{
    return NSObject.new.loginManager.userInfo.userid;
}

+ (NSString *)userID_String{
    return [@(NSObject.new.loginManager.userInfo.userid) stringValue];
}

//保存deviceToken
- (void)saveDeviceToken:(NSString *)token{
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:WNSaveDeviceTokenKey];
}
//获取deviceToken
- (NSString *)getDeviceToken{
    return [[NSUserDefaults standardUserDefaults] objectForKey:WNSaveDeviceTokenKey];
}
@end
